import { useUserStore } from '@/stores/user'
import { createApp, type Directive, type DirectiveBinding } from 'vue'
import Nopermission from '@/views/error/nopermission.vue'

/**
 * 自定义指令：判断是否有权限
 */
export const permission: Directive = {
  mounted(el: HTMLElement, binding: DirectiveBinding) {
    const permissionKey: string = binding.value as string
    // 如果没有权限，移除元素
    if (!handleCheckPermission(permissionKey)) {
      if (permissionKey.includes('查看')) {
        const placeholder = createApp(Nopermission).mount(el)
        el.appendChild(placeholder.$el)
      } else {
        el.remove()
      }
    }
  }
}

const handleCheckPermission = (permissionKey: string) => {
  const userStore = useUserStore()
  const userRoleList = userStore.getUsersActionRoles()
  return userRoleList.includes(permissionKey)
}
